ifndef ROOT_DIR
ROOT_DIR = .
endif

#-------------------------------
#	PART 1
#-------------------------------
DEBUG = 1

ifeq (1,$(DEBUG))
CFLAGS += -g
endif
CFLAGS += $(INCLUDE_DIR)

SOURCE_FOR_C = $(foreach source_file_1, $(SOURCES),$(filter %.c, $(source_file_1)))
DEPENDS_C    = $(addprefix obj/,$(SOURCE_FOR_C:.c=.c.d))
DEPENDS	     = $(DEPENDS_C)
OBJS         = $(DEPENDS_C:.c.d=.o) 
LIBS		 = $(wildcard $(ROOT_DIR)/lib/*.a)

#-------------------------------
#	PART 2
#-------------------------------
all:$(TARGET)
ifneq (1,$(MAIN))
$(TARGET): $(DEPENDS) $(OBJS) 
	@rm $(TARGET) -fr
	@echo "[LINK] $@"
	@$(AR) $(ARFLAGS) $@ $(OBJS)
else
$(TARGET):$(DEPENDS) $(LIBS) $(OBJS)
	@echo "[GEN]rom.bin generate..."
	@$(CC) $(ROOT_DIR)/test/obj/main.o $(LIBS) -o $(ROOT_DIR)/main
endif


#-------------------------------
#	PART 3
#-------------------------------
depends: $(DEPENDS)

obj/%.c.d : %.c
	mkdir -p obj/
	$(CC) -MM $(CFLAGS) $< > $@.$$$$; \
	sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$

obj/%.o: %.c
	@rm $(TARGET) -fr
	@echo "[NO ZIP] $< "
	@$(CC) $(CFLAGS) -c $^ -o $@ 

clean:
	@echo "[CLEAN]"
	@rm -rfv  *.o *.d *.tmp *.bin *.spz *.spgzip *.lzma *.text $(OBJS) $(DEPENDS) obj *.bak 
	@rm -rfv $(TARGET)
	@rm -rfv $(ROOT_DIR)/main
